package com.example.demo.controller;

import com.example.demo.req.ChatRequest;
import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Map;

@RestController
@RequestMapping("/api/deepseek")
public class DeepSeek4JController {

    @Autowired
    private DeepSeekClient deepSeekClient;

    //普通对话
    @PostMapping("chat")
    public Map<String, String> generate(@RequestBody ChatRequest request) {
        ChatCompletionRequest chatRequest = ChatCompletionRequest.builder()
                .model(ChatCompletionModel.DEEPSEEK_CHAT)
                .addUserMessage(request.getQuestion())
                .build();
        
        ChatCompletionResponse response = deepSeekClient.chatCompletion(chatRequest).execute();
        String content = response.choices().get(0).message().content();
        return Map.of("generation", content);
    }

    //流式返回
    @PostMapping(value = "chat-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> chatStream(@RequestBody ChatRequest request) {
        return deepSeekClient.chatFluxCompletion(request.getQuestion())
                .flatMap(chatResponse -> {
                    // 获取响应内容
                    String content = chatResponse.choices().get(0).delta().content();
                    // 防止content为null时跳过
                    if (content == null || content.trim().isEmpty()) {
                        return Flux.empty();
                    }
                    // 创建符合HTML页面期望的JSON格式
                    String jsonData = "{\"result\":{\"output\":{\"content\":\"" + content.replace("\"", "\\\"") + "\"}}}";
                    return Flux.just(ServerSentEvent.builder(jsonData).build());
                })
                // 在流结束时发送一个 [DONE] 事件
                .concatWithValues(ServerSentEvent.builder("[DONE]").build());
    }
}
